package sqlbuilder;

import java.util.List;
import java.util.StringJoiner;

/**
 * @Classname SqlBuilder
 * @Description TODO
 * @Date 2021/8/13 16:27
 * @Created by xx
 */
public class SqlBuilder {

    private static final String COUNT="SELECT COUNT(1) ";

    private final StringBuilder selectBuilder;

    private final StringBuilder stringBuilder;

    private final StringBuilder pageBuilder;


    /**
     * 添加查询sql
     * @param
     * @return
     */
    public SqlBuilder select(String select){
        String sql=selectBuilder.toString().toUpperCase();
        if(!sql.contains("SELECT")){
            selectBuilder.append("SELECT ");
        }
        selectBuilder.append(select);
        return this;
    }


    public SqlBuilder selectList(List<String> stringList){
        String select=String.join(",",stringList);
        this.select(select);
        return this;
    }


    public SqlBuilder from(String tableName){
        stringBuilder.append(" from ").append(tableName);
        return this;
    }

    /**
     * and 连接
     * @param field
     * @return
     */
    public SqlBuilder and(String field){
        appendCondition(stringBuilder,"and",field);
        return this;
    }

    /**
     * or 连接
     * @param field
     * @return
     */
    public SqlBuilder or(String field){
        appendCondition(stringBuilder,"or",field);
        return this;
    }

    public SqlBuilder eq(Object obj){
        stringBuilder.append(" = ").append("'").append(obj).append("'");
        return this;
    }

    public SqlBuilder like(Object obj){
        stringBuilder.append(" LIKE ").append("'%").append(obj).append("%'");
        return this;
    }

    public String getCountSql(){
       return COUNT+stringBuilder.toString();
    }

    public void page(Integer page,Integer size){
        page=(page-1)*size;
        pageBuilder.append(selectBuilder.toString()).append(stringBuilder.toString()).append(" LIMIT ").append(page).append(",").append(size);
    }

    public String getPage(){
        return pageBuilder.toString();
    }


    public String toString(){
        return selectBuilder.append(stringBuilder.toString()).toString();
    }

    public StringBuilder getStringBuilder(){
        return this.stringBuilder;
    }




    public SqlBuilder() {
        stringBuilder=new StringBuilder();
        pageBuilder=new StringBuilder();
        selectBuilder=new StringBuilder();
    }



    private void appendCondition(StringBuilder stringBuilder,String appendCondition,String field){
        String sql=stringBuilder.toString().toUpperCase();
        if(!sql.contains("WHERE")){
            appendCondition="WHERE";
        }
        stringBuilder.append(" ").append(appendCondition)
                .append(" ").append(field);
    }

}
